package com.metrictracker.ws;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.logging.Logger;

import org.restlet.representation.Representation;
import org.restlet.resource.ServerResource;

import com.metrictracker.model.Metric;
import com.metrictracker.model.MetricDao;
import com.metrictracker.util.ExceptionManager;



public class MetricTrackerServerResource extends ServerResource {

	private static final Logger log = Logger.getLogger(MetricTrackerServerResource.class.getName());
	
	protected HashMap<String, String> getParameters (Representation entity) throws IOException {
		//read it with BufferedReader
		BufferedReader br = new BufferedReader(new InputStreamReader(entity.getStream()));
		StringBuilder sb = new StringBuilder();

		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		} 

		String[] result = sb.toString().split("&");
		HashMap<String, String> parameters = new HashMap<String, String>();
		for (int x=0; x<result.length; x++) {
			String[] parameter = result[x].split("=");
			String parameterKey = URLDecoder.decode(parameter[0], "UTF-8");
			String parameterValue = URLDecoder.decode(parameter[1], "UTF-8");
			System.out.println (parameterKey + "=" + parameterValue);
			parameters.put(parameterKey, parameterValue);
		}
		br.close();
		return parameters;
	}

	protected Metric getMetric () {
		MetricDao metricDao = new MetricDao();
		String metricName = null;
		try {
			metricName = URLDecoder.decode((String) getRequestAttributes().get("metricName"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			ExceptionManager.logException(log, e);
			return null;
		}
		return metricDao.getMetric(metricName);
	}
}
